from piston.handler import BaseHandler
import datetime
from django.utils import simplejson

from models import Carpool
from models import Location


class StreamHandler( BaseHandler):
		allow_method =('GET', 'POST','PUT', 'DELETE')
		
		#for GET method
		@classmethod
		def read( self, request, querystring ):
				try:
				initiator_id=request.GET.get('user_id')
				objects = Carpool.objects.filter(initiator=initiator_id)
				if len(objects) == 0:
					raise Exception("no record")
				else:
					objects = [StreamHandler.produceJSON(o)
                    				for o in objects ]
					if len(objects) == 1:
						objects = objects[0]
				except:
					return 'FAILED'
				else:
					return objects
		
		#for POST method
		@classmethod
		def create( self, request, querystring):
				try:
				json_data = simplejson.loads(request.raw_post_data)
				
				new_carpool = Carpool(
				initiator = json_data['initiator'],
				init_time = json_data['init_time'],			
				description = json_data['description']
				)
				new_carpool.save()
				except:
					return 'FAILED'
				else:
					return 'SUCCESS'
		
		#for PUT method, define update method
		@classmethod
		def update( self, request, querystring):

				json_data = simplejson.loads(request.raw_post_data)

				return
				
		#for DELETE method, define delete method
		@classmethod
		def delete(self, request, querystring):
				carpoolno=request.GET.get('id')
				record = Users.objects.get(carpool_no=carpoolno)
				
				record.delete()
				return
					
		@staticmethod
		def produceJSON(retobj):
			retval = {}
			retval['id'] = retobj['id']
			retval['initiator'] = retobj['initiator']
			retval['init_time'] = retobj['init_time']
			retval['description'] = retobj['description']
			retval['status'] = retobj['status']
			retval['from_location'] = retobj['from_location']
			retval['to_location'] = retobj['to_location']
			retval['departure_time'] = retobj['departure_time']
			retval['arrival_time'] = retobj['arrival_time']
			retval['seat_num'] = retobj['seat_num']
			retval['seat_rem'] = retobj['seat_rem']
			retval['unit_price'] = retobj['unit_price']
			retval['pickup'] = retobj['pickup']			
			return retval
			
		@staticmethod
		def saveNewCarpool():

			new_carpool=Carpool(
				initiator="yang",
				init_is_provider=True,
				init_time=datetime.datetime.strptime("2012-04-12 15:30","%Y-%m-%d %H:%M"),
				description="Test carpool",
				provider="yang",
				status="pending",
				from_location=
				Location
				(
					longitude="120",
					latitude="30",
					description="University Campus"
				),
				to_location=
				Location
				(
					longitude="121",
					latitude="31",
					description="Shopping mall"
				),
				depature_time=datetime.datetime.strptime("2012-04-12 15:30","%Y-%m-%d %H:%M"),
				arrival_time=datetime.datetime.strptime("2012-04-12 15:30","%Y-%m-%d %H:%M"),
				seat_num=4;
				seat_rem=4,
				unit_price=10.00,
				pickup=False
			)

			new_carpool.save()
			return
			